package com.frp.lib.handler;

import com.frp.lib.message.Message;
import com.frp.lib.message.PackMsg;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * Created by hujianjun on 11/29 0029.
 */
public class MessageDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() <9)
            return;
        in.markReaderIndex();

        byte type = in.readByte();
        long length = in.readLong();
        if (in.readableBytes() < length) {
            in.resetReaderIndex();
            return;
        }

        in.resetReaderIndex();
        byte[] data = new byte[(int)length + 9];    //data len + len size + type size
        in.readBytes(data);

        Message msg = PackMsg.unpack(data);
        if (null != msg) {
            out.add(msg);
        }
    }
}
